<template>
  <div class="common-layout">
     <el-container>
         <el-header class="header_activate">
            <div class="draw">
                <el-drawer v-model="state.drawer" title="试卷增加题目" direction="ttb" size="70%">
                    <template #header>
                        <h4>修改试卷</h4>
                    </template>
                    <template #default>
                        <el-form :model="state.updatePaperForm" :rules="state.rules" ref="paperRef" label-width="100px" class="paperForm">
                            <el-form-item label="标题：" prop="title">
                                <el-input v-model="state.updatePaperForm.title" clearable/>
                            </el-form-item>
                            <el-form-item label="年级：" prop="grade">
                                <el-select v-model="state.updatePaperForm.grade" class="m-2" placeholder="选择年级" size="small" @change="typeSelectChange">
                                    <el-option
                                    v-for="item in paperGradeOption"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>            
                            </el-form-item>
                            <el-form-item label="附件">
                                <el-upload
                                    ref="uploadFileRef"
                                    name="file"
                                    :headers="{
                                    token: state.token
                                    }"
                                    class="upload-demo"
                                    drag
                                    :file-list="fileList"
                                    :action="state.uploadFileServer"
                                    accept=".docx,.doc,.pdf"
                                    :multiple="false"
                                    :show-file-list="true"
                                    :on-success="handleSuccess"
                                    :on-error="handleError"
                                    :auto-upload="true"
                                >
                                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                                    <div class="el-upload__text">
                                            文件拖拽这里或 <em>点击上传</em>
                                    </div>
                                    <template #tip>
                                    <div class="el-upload__tip">
                                        注意:只能上传docx/doc/pdf文件,且文件大小不超过8MB
                                    </div>
                                    </template>
                                </el-upload>
                            </el-form-item>
                            <el-form-item>                                
                                <el-button type="warning" @click="state.drawer=false">取消</el-button>
                                <el-button type="success" @click="submitUpdatePaper()" >确定</el-button>
                            </el-form-item>
                        </el-form>
                    </template>
                    
                    <template #footer>                
                        <div style="flex: auto">
                        <el-button type="warning" @click="state.drawer=false">取消</el-button>                  
                        
                        </div> 
                    </template>
                </el-drawer>
            </div>
            <div><h3>我录入的试卷</h3></div>            
             <div class="search_activate" id="top_position"> 
                 <el-input v-model="state.input_keyword" placeholder="输入试卷标题关键字" />
                 <el-button type="warning" :icon="Search" @click="searchQuestionContentClick"></el-button> 
             </div>
             <div class="filter">
                 <el-dropdown @command="handleCommand">
                     <span class="el-dropdown-link">
                         时间筛选
                     <el-icon class="el-icon--right">
                         <arrow-down />
                     </el-icon>
                     </span>
                     <template #dropdown>
                     <el-dropdown-menu>    
                        <el-dropdown-item command="0">无限制</el-dropdown-item>                    
                         <el-dropdown-item command="7">近7天</el-dropdown-item>
                         <el-dropdown-item command="15">近15天</el-dropdown-item>
                         <el-dropdown-item command="30">近30天</el-dropdown-item>
                         <el-dropdown-item command="60" disabled>近60天</el-dropdown-item>
                         <el-dropdown-item command="90">近90天</el-dropdown-item>
                         <el-dropdown-item command="180" >近半年</el-dropdown-item>                         
                     </el-dropdown-menu>
                     </template>
                 </el-dropdown>
             </div>
         </el-header>
         <el-divider />
         <el-main>
            <div><h3>试卷被设置为上线和公有，才能被其他用户浏览</h3></div>
             <el-table class="tableClass" :data="state.paperList" stripe                   
                 :header-cell-style="{ background: '#eef1f6', color: '#606266' }"                    
                  border
             > 
                 <el-table-column type="index" width="45" label="序" />              
                 <el-table-column width="60" property="grade" label="年级"/>   
                 <el-table-column width="250" property="title" label="标题" />
                 <el-table-column width="65" label="题目"> 
                      <template #default="scope"> 
                          <el-button size="small" type="primary" @click="viewPaperQuestionsClick(scope.$index)">详</el-button>
                      </template>
                  </el-table-column>
                  <el-table-column width="75" property="open_level" label="公开"/>
                  <el-table-column width="80" property="online" label="上/下线"/>
                 <el-table-column width="115" property="add_time" label="录入日期"/> 
                 <el-table-column width="75" label="审核">
                    <template #default="scope">
                        <el-text v-if="scope.row.application_info != undefined">{{ scope.row.application_info.status_cn }}</el-text>
                        <el-button v-if="scope.row.application_info == undefined" text type="success" @click="onlineClick(scope.row.id, scope.row.is_joint)">申请上线</el-button>
                    </template>
                </el-table-column>
                 <el-table-column align="center" width="110" label="操作" >                  
                     <template #default="scope">
                        <div class="operate">
                            <el-tooltip class="box-item" effect="dark" content="设为公开" placement="top" v-if="scope.row.open_level==='private'">                         
                                <el-icon style="width: 1em; height: 1em; margin-right: 8px" @click="SetPublicOrPrivateClick(scope.row.id,'public')">
                                    <Unlock />
                                </el-icon>
                            </el-tooltip>
                            <el-tooltip class="box-item" effect="light" content="设为私藏" placement="top" v-else>
                                <Lock style="width: 1em; height: 1em; margin-right: 8px" @click="SetPublicOrPrivateClick(scope.row.id,'private')" />
                            </el-tooltip>
                            <el-tooltip class="box-item" effect="light" content="申请上线" placement="top" v-if="scope.row.online===false"> 
                                <Top style="width: 1em; height: 1em;margin-right: 8px" @click="onlineClick(scope.row.id, scope.row.is_joint)" />
                            </el-tooltip>
                            <el-tooltip class="box-item" effect="dark" content="修改试卷" placement="top"> 
                                <Edit style="width: 1em; height: 1em;" @click="updatePaperClick(scope.row,scope.row.id)" />
                            </el-tooltip>
                            <el-popconfirm
                                confirm-button-text="在线"
                                cancel-button-text="文件"
                                :icon="InfoFilled"
                                icon-color="#626AEF"
                                title="选择试卷的录入方式"
                                @confirm="confirmEvent(scope.row.id,scope.row.title,scope.row.publish_time,scope.row.subject)"
                                @cancel="cancelEvent(scope.row.id, scope.row.subject)"
                                placement="top"
                            >
                                <template #reference>                                       
                                    <FolderAdd style="width: 1em; height: 1em;margin-right: 8px"/>                                                                          
                                </template>
                            </el-popconfirm>
                            <el-tooltip class="box-item" effect="light" content="查看试卷" placement="top" v-if="scope.row.file.length>0" >
                                <Document style="width: 1em; height: 1em;" @click="onClickViewFile(scope.row.file)" />
                            </el-tooltip>
                        </div>
                     </template>
                 </el-table-column>
             </el-table>
             
             <el-pagination
             background
             layout="total, pre, pager, next"
             :total="state.total"                
             :page-size="state.pageSize"            
             @current-change="handleCurrentChange"
             />
         </el-main>
         <ShowQuestionReadOnlyDialog ref="showQuestionReadOnlyDialog" :questionList="state.paperquestionList"></ShowQuestionReadOnlyDialog>       
        </el-container>
 </div>
</template>
<script setup>

import { Search, Unlock, Lock, Top, Document, ArrowDown, Edit,FolderAdd,InfoFilled} from '@element-plus/icons-vue'
import {onMounted,  reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from '@/utils/axios'
import ShowQuestionReadOnlyDialog from '@/views/ShowQuestionReadOnlyDialog.vue'
import { useRouter } from 'vue-router'
import { localGet, uploadFileServer, baseUrl_noapi, onlinePreview} from '@/utils'
import { Base64 } from 'js-base64';

const router = useRouter()
const uploadFileRef = ref(null)
const fileList = ref([])
const showGuidePaperFileDialog = ref(null)
const showQuestionReadOnlyDialog = ref(null)
const state = reactive({
  uploadFileServer,
  token:localGet('token') || "",
  input_keyword: '',
  days: 0,
  applicationList: [],
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 10, // 分页大小
  lastGetApplicationsMethod: 'default',
  paperList:[],
  paperquestionList:[],
  drawer:false,
  updatePaper_id:0,
  updatePaperForm:Object,
  rules: { // 规则
    title: [
      {required: 'true', message: '请填写试卷标题', trigger: ['change']}
    ],      
    grade: [
      { required: 'true', message: '请选择年级', trigger: ['change'] }
    ],
  },
})
const paperRef=ref(null)
// 查看文件
const onClickViewFile = (file) =>{
  console.log('file:',file)
  file = baseUrl_noapi + file
  window.open(onlinePreview + encodeURIComponent(Base64.encode(file)));
}

// 在线录入题目，跳转相应的路由页面
const confirmEvent = (id,title,publish_time,subject_id) => {
    console.log('标题!',title)
    console.log('subject_id:', subject_id)
    router.push({path:'/addPaperManual', query:{id:id,title:title,publish_time:publish_time,subject_id:subject_id}})
  }
// word导入题目，跳转到相应的页面
const cancelEvent = (id,subject) => {
    console.log('cancel and subject:', subject)
    if(parseInt(subject)==3){
        router.push({path:'/addPaperByFileStepOne', query:{importQuestionType:'importQuestionsSupplementPaper', id:id, subject: 'vocational'}})
    }else{
        router.push({path:'/addPaperByFileStepOne', query:{importQuestionType:'importQuestionsSupplementPaper', id:id, subject: 'senior'}})
    }

}
const paperGradeOption = [{ value : 1, label : '高一',}, {value : 2,label : '高二',},{value : 3,label : '高三',}]
// 默认方式获取试卷，即没有限制
const getPapersByDefault=()=>{
    let params = {
        days: state.days,
        page: state.currentPage,
        size: state.pageSize,
    }
    state.lastGetApplicationsMethod = 'default'
    console.log("默认方式获取试卷", params)
    axios.get(`/PaperModelViewSet/days_and_owner`, {params}).then(res => {
      console.log('服务器返回试卷：',res)
        if (res.code==200){
            console.log("获取录入试卷成功：", res)
            state.paperList = res.data.results
            state.total = res.total
        }else{       
            console.log("error", res.message)
        }
    })
    .catch((error)=>{
        console.log("获取录入试卷失败", error)
    })
}
// 通过搜索学科得到试卷
const getPapersBySearch=()=>{
    let params = { 
        query_key: state.input_keyword,
        page: state.currentPage,
        size: state.size,
    }
    state.lastGetApplicationsMethod = 'search'
    axios.get(`/PaperModelViewSet/search/`, {params}).then(res => {
        if (res.code==200){
            console.log("搜索结果：", res)
            state.paperList = res.data.results
            state.total = res.total
        }else{
            ElMessage.error("没有查询到记录")    
            console.log("error", res.message)
        }
    })
    .catch((error)=>{
        console.log("获取数据错误：", error)
    })
}
// 初始化页面加载
onMounted(() => {
  console.log('初始化页面加载')
  getPapersByDefault()
})
//设置天数
const handleCommand=(command=7)=>{
 command = parseInt(command)
 state.days = command
 getPapersByDefault()
}
// 设置试卷公开或私密
const SetPublicOrPrivateClick=(id, open_level)=>{  
    let params = {
    pk: id,
    type: 0,
    open_level: open_level,
    days: state.days,
    }
    axios.patch(`/PaperModelViewSet/${params.pk}/setup_open_level/`, params).then(res => {
        if (res.code==200){
            // console.log("申请列表：", res)
            ElMessage.success("试卷公开程度操作成功，返回首页！")
            state.paperList = res.data.results
            // getPapersBySearch()
        }else if(res.code==1021){
            ElMessage.error("试卷id错误！")
        }        
        else if(res.code==1022){
            ElMessage.warning("此操作没有必要！")
            console.log("error", res)
        }else{
            ElMessage.error("此操作失败！")
        }
    })
    .catch((error)=>{
        console.log("获取数据错误：", error)
    })
}

// 滚到顶端
const scrollToTop=()=>{
 document.querySelector('#top_position').scrollIntoView(true);
}
//点击页码时触发
const handleCurrentChange = (newPage)=>{
    state.currentPage = newPage 
    if (state.lastGetApplicationsMethod == 'default'){
        getPapersByDefault()
    }else{
        getPapersBySearch()
    }
    scrollToTop()
}
// 通过路由参数id获取试卷获取题目
const getQuestionsByPaper=(paper_id)=>{
  axios.get("/GetQuestionsByPaper/",{
    params:{
      id: paper_id,
      page: 1,
      size: 50,
    }
  }).then(res => {
    if (res.code==200){
      state.paperquestionList = res.data.results    
    }else{
      ElMessage("获取题目失败")       
      console.log("error", res) 
      if(res.code==403){
        ElMessage.error("请重新登录")
        router.push("/login")
      }
    }        
  })
  .catch((error)=>{
    console.log("获取题目列表错误：", error)
  })
}
//点击查看试卷题目的按钮事件处理
const viewPaperQuestionsClick=(index)=>{  
    state.paperquestionList=state.paperList[index].questions
    showQuestionReadOnlyDialog.value.open(state.paperquestionList)
}
// 点击搜索事件按钮处理
const searchQuestionContentClick=()=>{    
    console.log("要搜索试卷啦")
    getPapersBySearch()
}
//点击更新试卷按钮，并从试卷列表中，获取该试卷的数据，开启抽屉，
const updatePaperClick=(obj,id)=>{
    state.updatePaper_id=id
    console.log("选择的试卷是：",obj)
    state.updatePaperForm = obj
    state.drawer=true
}
  // 选择年级段后，赋值给表单的相应字段
  const typeSelectChange=(value)=>{
    // console.log("选择题型改变了", value)
    state.updatePaperForm.grade=value
  }
  // 提交更改试卷信息
  const submitUpdatePaper=()=>{
    paperRef.value.validate((vaild, obj) => {
      if (vaild) {
        let params = {
          id: state.updatePaperForm.id,
          title: state.updatePaperForm.title,
          file: state.updatePaperForm.file,
          grade: state.updatePaperForm.grade,
        }
        axios.put(`/PaperModelViewSet/${state.updatePaper_id}/`, params).then((result) => {
          if(result.code==200){
            ElMessage.success( '操作成功')
            getPapersByDefault()
            state.drawer=false
          }else{
            console.log("提交错误", result)
          }
        }).catch((error)=>{
          console.log("更新试卷错误：", error)
        })
      }else{                //输出表单没有通过的原因
        console.log("表单没有通过！",obj)
        for (let key in obj) {
          console.log("具体错误：",obj[key][0].message)          
        }   
      }
    })
  }

   // 申请试题上线
   const onlineClick=(id, is_joint)=>{
    let params={ id:id }
    let backend_api = `/GeneralPaperApplicationModelViewSet/`
    // let localUser = localGet('user_information')
    if(is_joint == true || is_joint === 'true'){
        backend_api = `/JointPaperApplicationModelViewSet/`
    }
    axios.post(backend_api, params).then(res => {
          if (res.code==200){
              ElMessage.success("上线申请成功，请耐心等待管理员审核！")
          }else if(res.code==1024){
          ElMessage.error("你的申请已被管理员拒绝，请修改内容，并联系管理员！")
              console.log("error", res)
          }else if(res.code==1022){
              ElMessage.warning("你的申请已经提交，请耐心等待管理员审核！")
              console.log("error", res)
          }else{
            console.log("操作失败", res)
            ElMessage.error("此操作失败！")
          }
      })
      .catch((error)=>{
          console.log("获取数据错误：", error)
      })
  }

// 上传文档文件成功
const handleSuccess=(res)=> {
console.log("上传返回数据：",res)
  if(res.code==200){ 
    console.log("上传文件后的url：", res)
    ElMessage.success("上传文档成功！")
    state.updatePaperForm.file = res.data.results
  }else{
    ElMessage.warning("请重新选择文档")
    ElMessageBox.alert(
      res.message,
      '请检查试卷格式！',
      {
        dangerouslyUseHTMLString: true,
      }
    )
  }
}
// 上传失败处理
const handleError=(res)=>{
  console.log("上传文件失败：", res)
}
</script>

<style scoped>
.search_activate {
 display: flex;
 flex-flow: row nowrap;
 /* justify-content: space-between; */
 align-items: center;
 margin: 0 auto;
 height: 30px;
}
.header_activate{
 display: flex;
 flex-flow: row nowrap;
 justify-content:flex-start;
 align-items: center;
 padding: 0px;
 height: 30px;
 width:800px;
}
span{
 font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
 font-size: medium;
}
.tableClass .cell{   
 padding: 0!important;
 height: 20px!important;
 line-height: 20px!important;
 text-align: center;
 font-size: 10px;
}
.filter{
    background-color: rgb(219, 226, 221);
}
.operate{
    display: flex;
    flex-flow: row nowrap;
    justify-content:space-between;
    align-items: center;
    padding: 2px;   
}
</style>